import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import {{invokerPackage}}.JSON;

{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}}
@JsonDeserialize(using={{classname}}.{{classname}}Deserializer.class)
@JsonSerialize(using = {{classname}}.{{classname}}Serializer.class)
public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}} implements {{{.}}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-implements}} {
    private static final Logger log = Logger.getLogger({{classname}}.class.getName());

    public static class {{classname}}Serializer extends StdSerializer<{{classname}}> {
        public {{classname}}Serializer(Class<{{classname}}> t) {
            super(t);
        }

        public {{classname}}Serializer() {
            this(null);
        }

        @Override
        public void serialize({{classname}} value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
            jgen.writeObject(value.getActualInstance());
        }
    }

    public static class {{classname}}Deserializer extends StdDeserializer<{{classname}}> {
        public {{classname}}Deserializer() {
            this({{classname}}.class);
        }

        public {{classname}}Deserializer(Class<?> vc) {
            super(vc);
        }

        @Override
        public {{classname}} deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            JsonNode tree = jp.readValueAsTree();

            Object deserialized = null;
            {{#discriminator}}
            Class<?> cls = JSON.getClassForElement(tree, new {{classname}}().getClass());
            if (cls != null) {
                // When the OAS schema includes a discriminator, use the discriminator value to
                // discriminate the anyOf schemas.
                // Get the discriminator mapping value to get the class.
                deserialized = tree.traverse(jp.getCodec()).readValueAs(cls);
                {{classname}} ret = new {{classname}}();
                ret.setActualInstance(deserialized);
                return ret;
            }
            {{/discriminator}}
            {{#anyOf}}
            // deserialize {{{.}}}
            try {
                deserialized = tree.traverse(jp.getCodec()).readValueAs({{{.}}}.class);
                {{classname}} ret = new {{classname}}();
                ret.setActualInstance(deserialized);
                return ret;
            } catch (Exception e) {
                // deserialization failed, continue, log to help debugging
                log.log(Level.FINER, "Input data does not match '{{classname}}'", e);
            }

            {{/anyOf}}
            throw new IOException(String.format("Failed deserialization for {{classname}}: no match found"));
        }

        /**
         * Handle deserialization of the 'null' value.
         */
        @Override
        public {{classname}} getNullValue(DeserializationContext ctxt) throws JsonMappingException {
        {{#isNullable}}
            return null;
        {{/isNullable}}
        {{^isNullable}}
            throw new JsonMappingException(ctxt.getParser(), "{{classname}} cannot be null");
        {{/isNullable}}
        }
    }

    // store a list of schema names defined in anyOf
    public static final Map<String, Class<?>> schemas = new HashMap<String, Class<?>>();

    public {{classname}}() {
        super("anyOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}});
    }
{{> libraries/native/additional_properties }}
    {{#additionalPropertiesType}}
    /**
     * Return true if this {{name}} object is equal to o.
     */
    @Override
    public boolean equals(Object o) {
        return super.equals(o) && Objects.equals(this.additionalProperties, (({{classname}})o).additionalProperties);
    }

    @Override
    public int hashCode() {
        return Objects.hash(getActualInstance(), isNullable(), getSchemaType(), additionalProperties);
    }
    {{/additionalPropertiesType}}
    {{#anyOf}}
    public {{classname}}({{{.}}} o) {
        super("anyOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}});
        setActualInstance(o);
    }

    {{/anyOf}}
    static {
        {{#anyOf}}
        schemas.put("{{{.}}}", {{{.}}}.class);
        {{/anyOf}}
        JSON.registerDescendants({{classname}}.class, Collections.unmodifiableMap(schemas));
        {{#discriminator}}
        // Initialize and register the discriminator mappings.
        Map<String, Class<?>> mappings = new HashMap<String, Class<?>>();
        {{#mappedModels}}
        mappings.put("{{mappingName}}", {{modelName}}.class);
        {{/mappedModels}}
        mappings.put("{{name}}", {{classname}}.class);
        JSON.registerDiscriminator({{classname}}.class, "{{propertyBaseName}}", mappings);
        {{/discriminator}}
    }

    @Override
    public Map<String, Class<?>> getSchemas() {
        return {{classname}}.schemas;
    }

    /**
     * Set the instance that matches the anyOf child schema, check
     * the instance parameter is valid against the anyOf child schemas:
     * {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}
     *
     * It could be an instance of the 'anyOf' schemas.
     * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf).
     */
    @Override
    public void setActualInstance(Object instance) {
        {{#isNullable}}
        if (instance == null) {
           super.setActualInstance(instance);
           return;
        }

        {{/isNullable}}
        {{#anyOf}}
        if (JSON.isInstanceOf({{{.}}}.class, instance, new HashSet<Class<?>>())) {
            super.setActualInstance(instance);
            return;
        }

        {{/anyOf}}
        throw new RuntimeException("Invalid instance type. Must be {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}");
    }

    /**
     * Get the actual instance, which can be the following:
     * {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}
     *
     * @return The actual instance ({{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}})
     */
    @Override
    public Object getActualInstance() {
        return super.getActualInstance();
    }

    {{#anyOf}}
    /**
     * Get the actual instance of `{{{.}}}`. If the actual instance is not `{{{.}}}`,
     * the ClassCastException will be thrown.
     *
     * @return The actual instance of `{{{.}}}`
     * @throws ClassCastException if the instance is not `{{{.}}}`
     */
    public {{{.}}} get{{{.}}}() throws ClassCastException {
        return ({{{.}}})super.getActualInstance();
    }

    {{/anyOf}}

{{#supportUrlQuery}}

  /**
   * Convert the instance into URL query string.
   *
   * @return URL query string
   */
  public String toUrlQueryString() {
    return toUrlQueryString(null);
  }

  /**
   * Convert the instance into URL query string.
   *
   * @param prefix prefix of the query string
   * @return URL query string
   */
  public String toUrlQueryString(String prefix) {
    String suffix = "";
    String containerSuffix = "";
    String containerPrefix = "";
    if (prefix == null) {
      // style=form, explode=true, e.g. /pet?name=cat&type=manx
      prefix = "";
    } else {
      // deepObject style e.g. /pet?id[name]=cat&id[type]=manx
      prefix = prefix + "[";
      suffix = "]";
      containerSuffix = "]";
      containerPrefix = "[";
    }

    StringJoiner joiner = new StringJoiner("&");

    {{#composedSchemas.oneOf}}
    {{^vendorExtensions.x-duplicated-data-type}}
    if (getActualInstance() instanceof {{{dataType}}}) {
        {{#isArray}}
        {{#items.isPrimitiveType}}
        {{#uniqueItems}}
        if (getActualInstance() != null) {
          int i = 0;
          for ({{{items.dataType}}} _item : ({{{dataType}}})getActualInstance()) {
            joiner.add(String.format("%s{{baseName}}%s%s=%s", prefix, suffix,
                "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix),
                URLEncoder.encode(String.valueOf(_item), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
          }
          i++;
        }
        {{/uniqueItems}}
        {{^uniqueItems}}
        if (getActualInstance() != null) {
          for (int i = 0; i < (({{{dataType}}})getActualInstance()).size(); i++) {
            joiner.add(String.format("%s{{baseName}}%s%s=%s", prefix, suffix,
                "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix),
                URLEncoder.encode(String.valueOf(getActualInstance().get(i)), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
          }
        }
        {{/uniqueItems}}
        {{/items.isPrimitiveType}}
        {{^items.isPrimitiveType}}
        {{#items.isModel}}
        {{#uniqueItems}}
        if (getActualInstance() != null) {
          int i = 0;
          for ({{{items.dataType}}} _item : ({{{dataType}}})getActualInstance()) {
            if (_item != null) {
              joiner.add(_item.toUrlQueryString(String.format("%s{{baseName}}%s%s", prefix, suffix,
                  "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix))));
            }
          }
          i++;
        }
        {{/uniqueItems}}
        {{^uniqueItems}}
        if (getActualInstance() != null) {
          for (int i = 0; i < (({{{dataType}}})getActualInstance()).size(); i++) {
            if ((({{{dataType}}})getActualInstance()).get(i) != null) {
              joiner.add((({{{items.dataType}}})getActualInstance()).get(i).toUrlQueryString(String.format("%s{{baseName}}%s%s", prefix, suffix,
              "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix))));
            }
          }
        }
        {{/uniqueItems}}
        {{/items.isModel}}
        {{^items.isModel}}
        {{#uniqueItems}}
        if (getActualInstance() != null) {
          int i = 0;
          for ({{{items.dataType}}} _item : ({{{dataType}}})getActualInstance()) {
            if (_item != null) {
              joiner.add(String.format("%s{{baseName}}%s%s=%s", prefix, suffix,
                  "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix),
                  URLEncoder.encode(String.valueOf(_item), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
            }
            i++;
          }
        }
        {{/uniqueItems}}
        {{^uniqueItems}}
        if (getActualInstance() != null) {
          for (int i = 0; i < (({{{dataType}}})getActualInstance()).size(); i++) {
            if (getActualInstance().get(i) != null) {
              joiner.add(String.format("%s{{baseName}}%s%s=%s", prefix, suffix,
                  "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, i, containerSuffix),
                  URLEncoder.encode(String.valueOf((({{{dataType}}})getActualInstance()).get(i)), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
            }
          }
        }
        {{/uniqueItems}}
        {{/items.isModel}}
        {{/items.isPrimitiveType}}
        {{/isArray}}
        {{^isArray}}
        {{#isMap}}
        {{#items.isPrimitiveType}}
        if (getActualInstance() != null) {
          for (String _key : (({{{dataType}}})getActualInstance()).keySet()) {
            joiner.add(String.format("%s{{baseName}}%s%s=%s", prefix, suffix,
                "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix),
                getActualInstance().get(_key), URLEncoder.encode(String.valueOf((({{{dataType}}})getActualInstance()).get(_key)), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
          }
        }
        {{/items.isPrimitiveType}}
        {{^items.isPrimitiveType}}
        if (getActualInstance() != null) {
          for (String _key : (({{{dataType}}})getActualInstance()).keySet()) {
            if ((({{{dataType}}})getActualInstance()).get(_key) != null) {
              joiner.add((({{{items.dataType}}})getActualInstance()).get(_key).toUrlQueryString(String.format("%s{{baseName}}%s%s", prefix, suffix,
                  "".equals(suffix) ? "" : String.format("%s%d%s", containerPrefix, _key, containerSuffix))));
            }
          }
        }
        {{/items.isPrimitiveType}}
        {{/isMap}}
        {{^isMap}}
        {{#isPrimitiveType}}
        if (getActualInstance() != null) {
          joiner.add(String.format("%s{{{baseName}}}%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf(getActualInstance()), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
        }
        {{/isPrimitiveType}}
        {{^isPrimitiveType}}
        {{#isModel}}
        if (getActualInstance() != null) {
          joiner.add((({{{dataType}}})getActualInstance()).toUrlQueryString(prefix + "{{{baseName}}}" + suffix));
        }
        {{/isModel}}
        {{^isModel}}
        if (getActualInstance() != null) {
          joiner.add(String.format("%s{{{baseName}}}%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf(getActualInstance()), StandardCharsets.UTF_8).replaceAll("\\+", "%20")));
        }
        {{/isModel}}
        {{/isPrimitiveType}}
        {{/isMap}}
        {{/isArray}}
        return joiner.toString();
    }
    {{/vendorExtensions.x-duplicated-data-type}}
    {{/composedSchemas.oneOf}}
    return null;
  }
{{/supportUrlQuery}}

}
